<template>
  <div>
    <header>
      <BaseNavBar title="修改密码" :isNav="true" />
    </header>
    <main style="margin-top: 8px;">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field v-model="username" name="username" label="用户名" :readonly="true" />
          <van-field v-model="oldPwd" type="password" name="oldPwd" label="原密码"   placeholder="请输入原密码"/>
          <van-field v-model="password" type="password" name="password" label="新密码" placeholder="请输入新密码"
            :rules="[{ required: true, message: '请填写新密码' }]" />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button color="#4A90E2" round block type="primary" native-type="submit">
            修改密码
          </van-button>
        </div>
      </van-form>


    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showConfirmDialog } from 'vant';
import BaseNavBar from '@/components/BaseNavBar/index.vue';
import { getUserInfo,userUpdatePassword } from '@/apis/user';


const router = useRouter();
const username = ref('');
const password = ref('');
const oldPwd = ref('');


const onSubmit = (values) => {
  showConfirmDialog({
    title: `修改密码`,
    message: "修改密码后，需要重新登录，请谨慎操作！",
  })
    .then(async () => {
      try {
        const { code, msg } = await userUpdatePassword({
          oldPwd: values.oldPwd,
          password:values.password,
        });
        if (code === 200) {
          showToast('已成功修改密码');
          localStorage.clear();
          router.push('/')
          return
        }
        showToast(msg);
      } catch (error) {
        console.log(error, 'error');

      }
    })
    .catch(() => {

    });
};




const init = async () => {
  const { data = {} } = await  getUserInfo();
  username.value = data.username;
};

onMounted(() => {
  init()
});
</script>

<style lang="less" scoped></style>
